package com.whtq.front.common.util;

import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.*;

/**
 * Created by
 *
 * @author wmi
 * @date 2020/3/5 - 21:38.
 * @description
 */
@Slf4j
public class WeiXinSignUtil {

    public static String md5Sign(Map<String, String> params, String privateKey) {
        String signature = "";
        //过滤空值、sign与sign_type参数
        Map<String, String> sParaNew = paraFilter(params);
        String contentToSign = createSortedLinkString(sParaNew, false);
        contentToSign = contentToSign+"&key="+privateKey;
        log.info("jiamizifuchuang:"+contentToSign);
        signature = MD5Util.MD5Encode(contentToSign, "utf-8").toUpperCase();
        log.info("signature:"+signature);
        return signature;
    }

    private final static Map<Class, Field[]> cache = new HashMap<Class, Field[]>();

//    public static Map<String, String > getParameterMap(WxPayCallbackReq req) {
//        Map<String, String > params = new HashMap<String, String>();
//        Class instanceClass = req.getClass();
//
//
//        Field[] fs = cache.get(instanceClass);
//        if (fs == null) {
//            fs = instanceClass.getDeclaredFields();
//            cache.put(instanceClass,fs);
//        }
//        try {
//            for(int i = 0 ; i < fs.length; i++){
//                Field f = fs[i];
//                String key = f.getName();
//                //f.setAccessible(true); //设置些属性是可以访问的
//                String value = f.get(req).toString();//得到此属性的值
//                if (value!=null & !value.isEmpty()){
//                    params.put(key, value);
//                }
//            }
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        }
//        return params;
//    }

    /**
     * 将map转成xml
     * @param params
     * @return
     */
    public static String convertToXML(Map<String, String> params) {
        List<String> keys = new ArrayList<String>(params.keySet());
        StringBuffer content = new StringBuffer();
        content.append("<xml>");
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);
            content.append("<" + key + ">" + value + "</" + key + ">");
        }
        content.append("</xml>");
        return content.toString();
    }


//    public static String sha1Sign(Map<String, String> params) {
//        String signature = "";
//        //过滤空值、sign与sign_type参数
//        Map<String, String> sParaNew = paraFilter(params);
//        String contentToSign = createSortedLinkString(sParaNew, false);
//
//        signature = Sha1Util.getSha1(contentToSign);
//
//        return signature;
//    }


    /**
     * 除去数组中的空值和签名参数
     * @param sArray 签名参数组
     * @return 去掉空值与签名参数后的新签名参数组
     */
    public static Map<String, String> paraFilter(Map<String, String> sArray) {

        Map<String, String> result = new HashMap<String, String>();

        if (sArray == null || sArray.size() <= 0) {
            return result;
        }

        for (String key : sArray.keySet()) {
            String value = sArray.get(key);
            if (value == null || value.equals("") || key.equalsIgnoreCase("sign")
                    || key.equalsIgnoreCase("sign_type")) {
                continue;
            }
            result.put(key, value);
        }

        return result;
    }

    /**
     * 把数组所有元素排序，并按照“参数=参数值”的模式用“&”字符拼接成字符串
     * @param params 需要排序并参与字符拼接的参数组
     * @return 拼接后字符串
     */


    public static String createSortedLinkString(Map<String, String> params, boolean urlEncode)  {
        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);

        StringBuffer content = new StringBuffer();

        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);
            if (urlEncode) {
                try {
                    value = URLEncoder.encode(value, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    log.error(e.getMessage());
                }
            }
            if (i == keys.size() - 1) {//拼接时，不包括最后一个&字符
                content.append(key).append("=").append(value).append("");
            } else {
                content.append(key).append("=").append(value).append("&");
            }
        }

        return content.toString();
    }

    public static String getTimeStamp() {
        return String.valueOf(System.currentTimeMillis() / 1000);
    }



    public static String getNonceStr() {
        Random random = new Random();
        return MD5Util.MD5Encode(String.valueOf(random.nextInt(10000)), "utf-8");
    }


}
